package tk.mynoteapp.dev.demo04.genericobjectpool;

import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;

/**
 * 参考：
 * https://blog.csdn.net/u012855229/article/details/100866550
 * https://blog.csdn.net/qq838642798/article/details/54603450
 * https://blog.csdn.net/chaofanwei2/article/details/51291401
 */
public class MyJedisPool extends GenericObjectPool<Jedis> {
    public MyJedisPool(PooledObjectFactory<Jedis> factory, GenericObjectPoolConfig<Jedis> config) {
        super(factory, config);
    }

    public static void main(String[] args) {
        GenericObjectPoolConfig<Jedis> config = new GenericObjectPoolConfig<>();
        config.setMinIdle(10); // 最小空闲连接数， 默认值 DEFAULT_MIN_IDLE = 0
        config.setMaxTotal(10); // 最大连接数，默认值 DEFAULT_MAX_TOTAL = 8
        config.setMaxWaitMillis(30000); // 当连接池资源用尽后，调用者获取连接时的最大等待时间（单位 ：毫秒）；默认值 DEFAULT_MAX_WAIT_MILLIS = -1L， 永不超时
        MyJedisFactory jedisFactory = new MyJedisFactory("127.0.0.1", 6379);
        // 最终GenericObjectPool会使用List初始化一个池（容器）
        MyJedisPool jedisPool = new MyJedisPool(jedisFactory, config);

        Jedis jedis = null;
        try {
            jedis = jedisPool.borrowObject();
            jedis.select(0);
            jedis.set("test", "pooltest");
            System.out.println(jedisPool.getNumActive());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedisPool.returnObject(jedis);// 归还对象到池中
            }
            System.out.println(jedisPool.getNumActive());
        }
    }
}
